package com.xcity.db.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcity.game.map.Mines;

import naga.x.util.StringUtils;

public class MinesTypeHandler extends BaseTypeHandler<Mines>{

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Mines parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, parameter != null?parameter.toString() : "[]");
	}

	@Override
	public Mines getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return parse(rs.getString(columnName));
	}

	@Override
	public Mines getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return parse(rs.getString(columnIndex));
	}

	@Override
	public Mines getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return parse(cs.getString(columnIndex));
	}

	public static Mines parse(String json){
		if(StringUtils.isEmpty(json)){
			return new Mines(null, null);
		}
		String[] strs = StringUtils.split(json, ";");
		if(strs.length > 1){
			JSONObject map = JSON.parseObject(strs[1]);
			Map<Integer, List<Long>> newMap = new ConcurrentHashMap<Integer, List<Long>>();
			for(String idStr : map.keySet()){
				String val = map.getString(idStr);
				List<Long> arr = JSON.parseArray(val, Long.class);
				newMap.put(Integer.parseInt(idStr), arr);
			}
			return new Mines(null, newMap);
		}
		return new Mines(null, null);
	}
}
